import axios from 'axios'
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { getToken } from '@/utils/auth'
import {errorCode} from '@/utils/errorCode'
import {VUE_APP_BASE_URL,VUE_APP_BASE_API} from "@/config/config"
// 是否显示重新登录
export let isRelogin = { show: false };
console.log(VUE_APP_BASE_URL)
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// axios.defaults.headers['Access-Control-Allow-Origin'] = "*"
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: VUE_APP_BASE_API,
  // 超时
  timeout: 600000
})

// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  if (getToken() && !isToken) {
    config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.status || 200;
    // 获取错误信息
    const msg =   res.data.message || errorCode[code as keyof typeof errorCode] || errorCode['default']
    // 二进制数据则直接返回
    if(res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer'){
      return res.data
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
        ElMessageBox.confirm(msg || '登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        isRelogin.show = false;
        console.log("请求拦截");
        // store.dispatch('LogOut').then(() => {
        //   location.href = '/index';
        // })
      }).catch(() => {
        isRelogin.show = false;
      });
    }
      return Promise.reject(!!res.data.message ? res.data.message : '无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 500) {
      ElMessage({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      ElNotification.error({
        title: msg
      })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// // 通用下载方法
// export function download(url, params, filename,method ="post",config) {
//   downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
//   if(method == 'post') {
//     return service.post(url, params, {
//       transformRequest: [(params) => { return tansParams(params) }],
//       headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
//       responseType: 'blob',
//       ...config
//     }).then(async (data) => {
//       const isLogin = await blobValidate(data);

//       if (isLogin) {
//         const blob = new Blob([data])
//         saveAs(blob, filename)
//       } else {
//         const resText = await data.text();
//         const rspObj = JSON.parse(resText);
//         const errMsg =  rspObj.message || errorCode[rspObj.code] ||errorCode['default']
//         if (rspObj.status === 401) {
//             if (!isRelogin.show) {
//               isRelogin.show = true;
//               ElMessageBox.confirm(errMsg || '登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
//                 confirmButtonText: '重新登录',
//                 cancelButtonText: '取消',
//                 type: 'warning'
//               }
//             ).then(() => {
//               isRelogin.show = false;
//               console.log("请求拦截");
//               store.dispatch('LogOut').then(() => {
//                 location.href = '/index';
//               })
//             }).catch(() => {
//               isRelogin.show = false;
//             });
//           }
//         }else {
//           ElMessage.error(errMsg);
//         }
//       }
//       downloadLoadingInstance.close();
//     }).catch((r) => {
//       console.error(r)
//       ElMessage.error('下载文件出现错误，请联系管理员！')
//       downloadLoadingInstance.close();
//     })
//   }else if(method == 'get'){
//     return service.get(url, params, {
//       transformRequest: [(params) => { return tansParams(params) }],
//       headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
//       responseType: 'blob',
//       ...config
//     }).then(async (data) => {
//       const isLogin = await blobValidate(data);
//       if (isLogin) {
//         console.log(isLogin)
//         const blob = new Blob([data],{type: 'application/octet-stream'})
//         saveAs1(blob, filename)
//       } else {
//         const resText = await data.text();
//         const rspObj = JSON.parse(resText);
//         const errMsg = rspObj.message || errorCode[rspObj.code] || errorCode['default']
//         ElMessage.error(errMsg);
//       }
//       downloadLoadingInstance.close();
//     }).catch((r) => {
//       console.error(r)
//       ElMessage.error('下载文件出现错误，请联系管理员！')
//       downloadLoadingInstance.close();
//     })
//   }
// }

// // 通用下载方法
// export function downloadUrl(url, filename) {
//   downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
//   const isLogin = blobValidate(url);
//   if (isLogin) {
//     const blob = new Blob([url])
//     saveAs(blob, filename)
//   } else {
//     const resText = url.text();
//     const rspObj = JSON.parse(resText);
//     const errMsg = rspObj.message || errorCode[rspObj.code] || errorCode['default']
//     ElMessage.error(errMsg);
//   }
//   downloadLoadingInstance.close();
// }

// function saveAs1(blob,filename) {
//     if (typeof window.navigator.msSaveBlob !== 'undefined') {
//       // IE workaround for "HTML7007: One or more blob URLs were
//       // revoked by closing the blob for which they were created.
//       // These URLs will no longer resolve as the data backing
//       // the URL has been freed."
//       window.navigator.msSaveBlob(blob, filename);
//     } else {
//       const blobURL = window.URL.createObjectURL(blob);
//       const tempLink = document.createElement('a');
//       tempLink.style.display = 'none';
//       tempLink.href = blobURL;
//       tempLink.setAttribute('download', filename);

//       // Safari thinks _blank anchor are pop ups. We only want to set _blank
//       // target if the browser does not support the HTML5 download attribute.
//       // This allows you to download files in desktop safari if pop up blocking
//       // is enabled.
//       if (typeof tempLink.download === 'undefined') {
//         tempLink.setAttribute('target', '_blank');
//       }

//       document.body.appendChild(tempLink);
//       tempLink.click();
//       document.body.removeChild(tempLink);
//       window.URL.revokeObjectURL(blobURL);
//     }
//   }
export default service
